<template>
  <div class="account-management">
    <div class="header">
      <h2>账户管理</h2>
      <el-button type="primary" @click="showAddDialog">开设新账户</el-button>
    </div>
    <el-page-header class="page-header" @back="$router.go(-1)" />
    <!-- 账户列表表格 -->
    <el-table
        :data="accountList"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="accountNumber" label="账号" width="180" align="center" />
      <el-table-column prop="customerId" label="客户ID" width="100" align="center" />
      <el-table-column label="账户类型" width="120" align="center">
        <template #default="{ row }">
          <el-tag :type="row.type === 'SAVING' ? 'success' : 'primary'">
            {{ row.type === 'SAVING' ? '储蓄账户' : '支票账户' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="余额(元)" width="150" align="right">
        <template #default="{ row }">
          <span class="balance">¥{{ row.balance.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="开户时间" align="center">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template #default="{ row }">
          <el-button
              size="small"
              type="danger"
              plain
              @click="handleDelete(row.id)"
          >
            注销
          </el-button>
          <el-button
              size="small"
              type="primary"
              plain
              @click="$router.push({ name: 'accountTransactions', params: { id: row.id } })"
          >
            交易记录
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 开户对话框 -->
    <el-dialog v-model="addDialogVisible" title="开设新账户" width="500px">
      <el-form :model="addForm" :rules="rules" ref="addFormRef">
        <el-form-item label="客户ID" prop="customer_id">
          <el-input-number
              v-model="addForm.customer_id"
              :min="1"
              controls-position="right"
          />
        </el-form-item>
        <el-form-item label="账户类型" prop="type">
          <el-select v-model="addForm.type" placeholder="请选择账户类型">
            <el-option label="储蓄账户" value="SAVING" />
            <el-option label="支票账户" value="CHECKING" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddForm" :loading="adding">
          确认开设
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { accountApi } from '@/api'

export default {
  name: 'AccountList',
  setup() {
    // 数据状态
    const accountList = ref([])
    const loading = ref(false)
    const addDialogVisible = ref(false)
    const adding = ref(false)
    const addFormRef = ref(null)

    // 表单数据
    const addForm = ref({
      customerId: 1,
      type: 'SAVING'
    })

    // 表单验证规则
    const rules = {
      customer_id: [
        { required: true, message: '请输入客户ID', trigger: 'blur' },
        { type: 'number', min: 1, message: 'ID必须大于0', trigger: 'blur' }
      ],
      type: [
        { required: true, message: '请选择账户类型', trigger: 'change' }
      ]
    }

    // 格式化日期
    const formatDate = (isoString) => {
      try {
        const date = new Date(isoString)
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false
        }).replace(/\//g, '-')
      } catch {
        return isoString
      }
    }

    // 获取账户列表
    const fetchAccountList = async () => {
      loading.value = true
      try {
        const response = await accountApi.listAccounts()
        if (response.state === 2000) {
          accountList.value = response.data || []
        } else {
          ElMessage.error(response.message || '获取账户列表失败')
        }
      } catch (error) {
        ElMessage.error(`请求失败: ${error.message}`)
      } finally {
        loading.value = false
      }
    }

    // 删除账户
    const handleDelete = async (accountId) => {
      try {
        await ElMessageBox.confirm('确定要注销此账户吗？此操作不可撤销！', '警告', {
          confirmButtonText: '确认注销',
          cancelButtonText: '取消',
          type: 'warning'
        })

        const response = await accountApi.deleteAccount(accountId)
        if (response.state === 2000) {
          ElMessage.success('账户注销成功')
          fetchAccountList()
        } else {
          ElMessage.error(response.message || '注销失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error(`注销失败: ${error.message}`)
        }
      }
    }

    // 开户功能
    const showAddDialog = () => {
      addDialogVisible.value = true
    }

    const submitAddForm = async () => {
      try {
        await addFormRef.value.validate()
        adding.value = true

        const response = await accountApi.addAccount({
          customerId: addForm.value.customerId,
          type: addForm.value.type
        })

        if (response.state == 2000) {
          ElMessage.success('开户成功')
          addDialogVisible.value = false
          fetchAccountList()
        } else {
          ElMessage.error(response.message || '开户失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error(`开户失败: ${error.message}`)
        }
      } finally {
        adding.value = false
      }
    }

    // 初始化加载数据
    onMounted(fetchAccountList)

    return {
      accountList,
      loading,
      addDialogVisible,
      adding,
      addForm,
      addFormRef,
      rules,
      formatDate,
      handleDelete,
      showAddDialog,
      submitAddForm
    }
  }
}
</script>

<style scoped>
.account-management {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.balance {
  font-weight: bold;
  color: #409EFF;
}
</style>